package com.itlaobing.demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Classname SessionFilter
 * @Description TODO()
 * @Date 2020/11/13 0013 9:19
 * @Author by Administrator
 * @Version v1.0
 */
@WebFilter("/*")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 先拿到请求地址
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // servlet/login
        String uri = request.getRequestURI();

        // 判断是不是登录请求
        boolean isLogin = uri.contains("login.jsp") || uri.contains("login") || uri.contains("captcha");
        // 判断是不是静态资源
        boolean isResources = uri.contains("assets") || uri.endsWith(".css") || uri.endsWith(".jpg") || uri.endsWith("jpeg") || uri.endsWith(".js") || uri.endsWith(".png") || uri.endsWith("gif");
        // 判断是不是登录请求,如果是登录请求直接放行,验证码也放行 , 静态资源
        if (isLogin || isResources){
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            // session 中存储的 user 信息
            Object obj = request.getSession().getAttribute("user");
            if (obj != null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                response.sendRedirect("login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
